$(function () {
    var searchFundRecordBtn = $("#searchFundRecord");
    var initSourceTable = function () {

        // 初始化列表
        var table = $('#sourceList').DataTable({
            "processing": true,
            "serverSide": true,
            "bSort": false,
            "ajax": {
                "url": "user/listUserSourceData",
                "data": function (d) {
                    var dateRange = dateRangePicker.val().split(" - ");
                    d.startTime = new Date(dateRange[0]);
                    var endTime = moment(dateRange[1], "YYYY/MM/DD").endOf('day');
                    d.endTime = new Date(endTime);
                    d.source = $("#sourceSelect").val();
                    d.campaign = $("#campaignSelect").val();
                    d.term = $("#termSelect").val();

                    if (d.source !== '' || d.campaign !== '' || d.term !== '') {
                        d.length = -1;
                        $("#sourceList_length").hide();
                        $(".dataTables_paginate").hide();
                    } else {
//                        d.length = 20;
                        $("#sourceList_length").show();
                        $(".dataTables_paginate").show();
                    }
                    d.loginNameQuery = $("#loginNameQuery").val();
                },
                "type": "GET"
            },
            "columns": [
                {"data": "user"},
                {"data": "user"}, //transId
                {"data": "info"},
                {"data": "info"},
                {"data": "info"},
                {"data": "user"},
                {"data": "user"},
                {"data": "user"},
                {"data": "fund"},
                {"data": "totalInvest"},
                {"data": "bonus"}
            ],
            "aoColumnDefs": [{
                    "targets": 0,
                    "mRender": function (data, type, row) {
                        return '<a href="user/index/' + row.user.id + '" target="_blank">' + row.user.loginName + '</a>'
                    }
                }, {
                    "targets": 1,
                    "mRender": function (data, type, row) {
                        return data.mobile;
                    }
                }, {
                    "targets": 2, //金额
                    "mRender": function (data, type, row) {
                        return data.source || '-';
                    }
                }, {
                    "targets": 3, //资金类型
                    "mRender": function (data, type, row) {
                        return data.campaign || '-';
                    }
                }, {
                    "targets": 4, //操作类型
                    "mRender": function (data, type, row) {
                        return data.term || '-';
                    }
                }, {
                    "targets": 5, //注册时间
                    "mRender": function (data, type, row) {
                        return $.format.date(data.registerTime, "yyyy/MM/dd HH:mm");
                    }
                }, {
                    "targets": 6, //推荐人
                    "mRender": function (data, type, row) {
                        return row.referee !== null
                            ? '<a href="user/index/' + row.referee.id + '" target="_blank">' + row.referee.loginName + '</a>'
                            : '-';
                    }
                }, {
                    "targets": 7, //推荐人渠道
                    visible: false,
                    "mRender": function (data, type, row) {
                        return row.refereeChannel !== null
                            ? row.refereeChannel
                            : '-';
                    }
                }, {
                    "targets": 8, //可用余额
                    visible: false,
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return $.number(data.available, 2);
                    }
                }, {
                    "targets": 9, //投标金额
                    visible: false,
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return $.number(data);
                    }
                }, {
                    "targets": 10, //红包
                    visible: false,
                    "searchable": false,
                    "mRender": function (data, type, row) {
                        return $.number(data);
                    }
                }],
            "order": [5, 'desc'],
            "oLanguage": chinese,
            "language": {
                "decimal": ",",
                "thousands": ",",
            },
            "iDisplayLength": 20,
            "aLengthMenu": [
                [5, 10, 20, 50, 100, -1],
                [5, 10, 20, 50, 100, "全部"]
            ],
            //"sDom": 't<"dt-panelfooter clearfix"ip>',
            "sDom": '<"dt-panelmenu clearfix"l<"pull-right"T>r>t<"dt-panelfooter clearfix"ip>',
            "oTableTools": {
                "aButtons": [{
                        "sExtends": "xls",
                        "sButtonText": "导出为Excel"
                    }
                ],
                "sSwfPath": root_path + "/js/plugins/datatables/extensions/TableTools/swf/copy_csv_xls_pdf.swf"
            },
            "fnDrawCallback": function () {
                // 高亮显示搜索内容
                if ($("#loginNameQuery").val() !== "") {
                    $("#sourceList").highlight($("#loginNameQuery").val());
                }
                sys.btnStop(searchFundRecordBtn);
            }
        });

        $('#searchFundRecord').on('click', function () {
            sys.btnSpin(searchFundRecordBtn);
            table.ajax.reload();
        });

        /**
         * 显示/隐藏列
         */
        $('label.toggle-label input[type=checkbox]').on('change', function (e) {
            var checked = $(this).prop("checked"),
                col_index = $(this).attr('data-column'),
                column = table.column(col_index);

            if (checked) {
                column.visible(true);
            } else {
                column.visible(false);
            }
        });
    };

    var dateRangePicker = $('#daterangepicker');
    var initDateRangePicker = function () {
        var rangePast = {
            '今天': [moment(), moment()],
            '昨天': [moment().subtract('days', 1), moment().subtract('days', 1)],
            '最近7天': [moment().subtract('days', 6), moment()],
            '最近30天': [moment().subtract('days', 29), moment()],
            '本月': [moment().startOf('month'), moment().endOf('month')],
            '上个月': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')]
        };

        var rangeFuture = {
            '今天': [moment(), moment()],
            '未来7天': [moment(), moment().add('days', 6)],
            '未来30天': [moment(), moment().add('days', 29)],
            '未来60天': [moment(), moment().add('days', 59)],
            '本月': [moment().startOf('month'), moment().endOf('month')],
            '下个月': [moment().add('month', 1).startOf('month'), moment().add('month', 1).endOf('month')]
        };

        dateRangePicker.daterangepicker({
            ranges: rangePast,
            startDate: moment().subtract('days', 7),
            endDate: moment(),
            applyClass: "btn-primary btn-block",
            cancelClass: "btn-block",
            format: "YYYY/MM/DD",
            locale: {
                applyLabel: '确定',
                clearLabel: "取消",
                fromLabel: '开始时间',
                toLabel: '结束时间',
                weekLabel: '周',
                customRangeLabel: '选择范围',
                daysOfWeek: "日_一_二_三_四_五_六".split("_"),
                monthNames: "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),
                firstDay: 0
            },
            opens: "left"
        });


        var formatDate = function (date) {
            return $.format.date(new Date(date), "yyyy/MM/dd");
        };
        // 根据状态设定初始日期
        var defaultDate = formatDate(moment().subtract('days', 7)) + ' - ' + formatDate(moment());

        dateRangePicker.val(defaultDate);
        $(".daterangepicker .ranges ul li:last").hide();
        $(".daterangepicker .ranges .daterangepicker_start_input").remove();
        $(".daterangepicker .ranges .daterangepicker_end_input").remove();
        $(".daterangepicker .ranges .cancelBtn").remove();
    };

    var initSelection = function () {
        $.get("user/listRegSTC", function (res) {
            if (res) {
                var ss = res.source, cc = res.campaign, tt = res.term;
                for (var i = 0; i < ss.length; i++) {
                    if (ss[i]) {
                        $("#sourceSelect").append($("<option></option>").val(ss[i]).text(ss[i]));
                    }
                }
                for (var i = 0; i < cc.length; i++) {
                    if (cc[i]) {
                        $("#campaignSelect").append($("<option></option>").val(cc[i]).text(cc[i]));
                    }
                }
                for (var i = 0; i < tt.length; i++) {
                    if (tt[i]) {
                        $("#termSelect").append($("<option></option>").val(tt[i]).text(tt[i]));
                    }
                }
            }
        });
    };

    initDateRangePicker();
    initSourceTable();
    initSelection();
});